package com.boarsoft.rpc.http.jetty.servlet;

import javax.servlet.http.HttpServletRequest;

import org.eclipse.jetty.proxy.AsyncProxyServlet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.boarsoft.rpc.core.RpcContext;

public class GatewayServlet extends AsyncProxyServlet {
	private static final Logger log = LoggerFactory.getLogger(GatewayServlet.class);
	
	private static final long serialVersionUID = -4634847690862338373L;
	
	@Autowired
	protected RpcContext rpcContext;

	@Override
	protected String rewriteTarget(HttpServletRequest req) {
//		String uri = req.getRequestURI().substring(1);
//		int i = uri.indexOf("/");
//		if (i < 1) {
//			return req.getRequestURL().toString();
//		}
//		String app = uri.substring(0, i);
		String key = req.getHeader("service");
		String addr = rpcContext.getProvider(key);
		if (addr == null) {
			log.warn("Can not found provider {} for service {}", addr, key);
			return req.getRequestURL().toString();
		}
		log.debug("Found provider {} for service {}", addr, key);
		String[] a = addr.split(":");
		String url = new StringBuilder("http://").append(a[0]).append(":1")//
				.append(a[1]).append(req.getRequestURI()).toString();
		log.info("Rewrite target url to {}", url);
		return url;
	}
}
